import Taro from "@tarojs/taro";
import ApiUser from "./user";
import useAppStore from "@/store";
import request from "@/utils/request";
import { ACCESSTOKEN } from "@/utils/constant";

import { TUserInfo } from "@/global";
import tokenManager from "@/utils/tokenManager";

/**
 * 静默登录
 */
export const SilenceAuthLogin = async () => {
  const { code } = await Taro.login();

  const data = await request(
    {
      url: ApiUser.wxLogin,
      method: "POST",
      data: { code },
    },
    { showErrorToast: false, tokenAuth: false }
  ).catch((error) => {
    return Promise.reject({ ...error, forceLogin: error.code == 500 || error.data?.code == 500});
  });

  // @ts-expect-error
  Taro.setStorageSync(ACCESSTOKEN, data.accessToken);

  // 主动获取/更新 用户信息
  await getUserInfo();
};

/**
 * 获取用户信息
 */
export const getUserInfo = async () => {
  const data = (await request(
    {
      url: ApiUser.userInfo,
      method: "POST",
    },
    { showErrorToast: false }
  )) as { user_info: TUserInfo };

  useAppStore.getState().updateUserInfo(data.user_info);
};

/**
 * 清除登录信息
 */
export const clearLoginInfo = () => {
  tokenManager.clear();
  useAppStore.getState().logout();
};
